<template>
  <div>
      <div class="search">
        <el-input style="width:400px" placeholder="请输入姓名" @change="inputChange" v-model="input" size="medium" clearable> </el-input>   
        <el-button type="primary" style="margin-left:20px" @click="search">搜索</el-button>  
        <el-button type="primary" style="margin-left:300px" @click="download">打包下载</el-button>
      </div>     
  </div>
</template>

<script>
import JSZip from "jszip";
import FileSaver from "file-saver";
export default {
  name: "search",
  data() {
    return {
      input: "",
      imageNameList: [],
    };
  },
  props: {
    arrImg: {
      type: Array,
    },
    imgData: {
      type: Array,
    },
  },
  methods: {
    //输入框失去焦点时触发的事件，参数为输入的值
    inputChange() {
      this.$emit("inputChange", this.input);
    },
    //搜索按钮点击事件
    search() {
      this.$emit('searchClict',this.input);
      this.$message({
        message: "搜索",
      });

    },
    //打包图片按钮点击事件
    download() {
      this.$message({
        message: "打包下载",
      });
      console.log(this.arrImg);
      console.log(this.imgData);
      this.imgData.forEach((item)=>{
          this.imageNameList.push(`${item.className}${item.nickName}${item.createTime}`)
      })
      this.downloadImgList(this.arrImg,this.imageNameList)
    },
    //打包图片具体实现函数，以及调用JSZip和FileSaver,参数为要下载的图片地址数组，和下载之后所对应的名称数组
    downloadImgList(arr,imgNameList) {
      var blogTitle = "打包图片";
      var zip = new JSZip();
      var imgs = zip.folder(blogTitle);
      var baseList = [];
      // 要下载图片的url
      //   var arr = this.arrImg;
      // 下载后图片的文件名，个数应与arr对应
      //   var imgNameList = ["图片1", "图片2"];

      for (var i = 0; i < arr.length; i++) {
        let image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");

        image.onload = function () {
          let canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;

          let context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);

          let url = canvas.toDataURL(); // 得到图片的base64编码数据
          canvas.toDataURL("image/png");

          baseList.push(url.substring(22)); // 去掉base64编码前的 data:image/png;base64,
          if (baseList.length === arr.length && baseList.length > 0) {
            for (let k = 0; k < baseList.length; k++) {
              imgs.file(imgNameList[k] + ".png", baseList[k], { base64: true });
            }
            zip.generateAsync({ type: "blob" }).then(function (content) {
              // see FileSaver.js
              FileSaver.saveAs(content, blogTitle + ".zip");
            });
          }
        };
        image.src = arr[i];
      }
    },
  },
};
</script>

<style  scoped>
.search {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>>

